package com.dapeng.jackson.serializer;

import com.dapeng.jackson.abstracts.BaseJKAnnotationSerializer;
import com.dapeng.jackson.annotations.JKByteFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @BelongProject study
 * @BelongPackage com.dapeng.jackson.annotations
 * @Description TODO
 * @ClassName JKByteFormatSerializer
 * @Author xupenghong
 * @Date 2024/9/13 15:56
 * @Version 1.0.0
 */
public class JKByteFormatSerializer extends BaseJKAnnotationSerializer<JKByteFormat, Number> {

    @Override
    public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            return;
        }

        JKByteFormat.Unit type = this.annotation.type();
        JKByteFormat.Unit convert = this.annotation.convert();
        int scale = this.annotation.scale();
        String unitSymbol = this.annotation.unit();

        BigDecimal bigValue = new BigDecimal(value.toString());
        BigDecimal result = convertValue(bigValue, type, convert, scale);

        if (!unitSymbol.isEmpty()) {
            gen.writeString(result + unitSymbol);
        } else {
            gen.writeNumber(result);
        }
    }

    private BigDecimal convertValue(BigDecimal bigValue,
                                    JKByteFormat.Unit type,
                                    JKByteFormat.Unit convert, int scale) {

        if (type.equals(convert)) {
            return bigValue.setScale(scale, RoundingMode.HALF_UP);
        }

        if (type.equals(JKByteFormat.Unit.BYTE)) {
            if (convert.equals(JKByteFormat.Unit.KB)) {
                return bigValue.divide(BigDecimal.valueOf(1024), scale, RoundingMode.HALF_UP);
            } else if (convert.equals(JKByteFormat.Unit.MB)) {
                return bigValue.divide(BigDecimal.valueOf(1024 * 1024), scale, RoundingMode.HALF_UP);
            } else if (convert.equals(JKByteFormat.Unit.GB)) {
                return bigValue.divide(BigDecimal.valueOf(1024 * 1024 * 1024), scale, RoundingMode.HALF_UP);
            }
        }

        return null;
    }
}
